package jp.sourceforge.akjrcp.util;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class NewIOFileCopy {
private static int MAX_COPY = 1024*1024*4;
private File srcFile;
private File destFile;
private boolean canceling;
public NewIOFileCopy(File srcFile,File destFile){
	this.srcFile=srcFile;
	this.destFile=destFile;
}
public boolean isCanceling() {
	return canceling;
}
public void setCanceling(boolean canceling) {
	this.canceling = canceling;
}

public File getSrcFile() {
	return srcFile;
}
public void setSrcFile(File srcFile) {
	this.srcFile = srcFile;
}
public File getDestFile() {
	return destFile;
}
public void setDestFile(File destFile) {
	this.destFile = destFile;
}

/*
 * warnning 
 * this code clash OS easily when dest file ejected.
 */
public int exec() throws IOException{
	
	FileChannel srcChannel = new FileInputStream(getSrcFile()).getChannel();
    FileChannel destChannel = new FileOutputStream(getDestFile()).getChannel();
    int myMax;
    if(MAX_COPY>getSrcFile().length()){
    	myMax=MAX_COPY;
    }else{
    	myMax=(int) getSrcFile().length();//maybe ok
    }
    try {
        long size = srcChannel.size();
        long index = 0;
        while (index < size && !canceling) {
           
            int length;
            if (index + myMax < size) {
                length = myMax;
            } else {
                length = (int)(size - index);
            }
              
           
            ByteBuffer srcBuffer= srcChannel.map(FileChannel.MapMode.READ_ONLY,index, length);

            if(getDestFile().exists()){
            	destChannel.write(srcBuffer);
            }else{
            	//warning
            	//log.info("dest not found:"+getDestFile());
            }
            
            index += length;
        }
    }catch(IOException e){
    	throw e;
    }
    
    finally {
    	try{
        srcChannel.close();
        srcChannel=null;
        destChannel.close();
        destChannel=null;
    	}catch (Exception e) {
    		//ignore closing exception
			e.printStackTrace();
		}
        System.gc();//for dispose channel lock,other can't delete file
    }
    
	/*
	 * old style so slow.
	BufferedInputStream binput=new BufferedInputStream(new FileInputStream(srcFile));
	BufferedOutputStream boutput=new BufferedOutputStream(new FileOutputStream(destFile));
	int b;
	while((b=binput.read())!=-1 && !canceling){
		boutput.write(b);
	}
	boutput.close();
	binput.close();
	*/
	if(canceling){
		//canceld;
		return 1;
	}
	return 0;
}

}
